package com.ustcinfo.study.mr.xuzongbao;
/**
 * �ڼ�Ⱥ���ύmapreduce�������ָ�
 * hadoop jar *.jar mainclass ����һ  ������....
 */
import java.io.IOException;
import java.util.Iterator;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;


public class WordCount {
	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		Job job = Job.getInstance();
		job.setJobName("MyWordCount");
		
		job.setJarByClass(WordCount.class);
		job.setMapperClass(MyMapper.class);
		job.setReducerClass(MyReducer.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		
		job.waitForCompletion(true);//�ύ��Ⱥ�Լ��ȴ����

	}
	
	private static class MyMapper extends Mapper<Object, Text, Text, IntWritable>{
		private static final IntWritable count = new IntWritable(1);
		
		@Override
		protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
			//����ȡ��һ������ת��Ϊstring����
			String line = value.toString();
			String[] arr = line.split(" ");
			for(String s:arr) {
				Text text = new Text();
				text.set(s);
				context.write(text, count);
				
			}
		}
	}
	
	private static class MyReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
		@Override
		protected void reduce(Text text, Iterable<IntWritable> iter, Context context) throws IOException, InterruptedException {
			//ÿ�δ������һ��keyֵ����Ӧһ���ɵ�������ֵ����
			int sum = 0;
			Iterator<IntWritable> itor = iter.iterator();
			while(itor.hasNext()) {
				sum += itor.next().get();
			}
			context.write(text, new IntWritable(sum));
		}
	}
	
	
}
